package com.businesscard.system.controller;

import com.businesscard.system.entity.UserGroup;
import com.businesscard.system.entity.User;
import com.businesscard.system.service.UserGroupService;
import com.businesscard.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户组管理控制器
 */
@Controller
@RequestMapping("/admin/usergroup")
public class UserGroupController {

    @Autowired
    private UserGroupService userGroupService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户组管理页面
     */
    @GetMapping("")
    public String userGroupPage(Model model) {
        return "admin/usergroup-management";
    }
    
    /**
     * 获取所有用户组
     */
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> getAllGroups() {
        Map<String, Object> result = new HashMap<>();
        List<UserGroup> groups = userGroupService.getAllGroups();
        result.put("success", true);
        result.put("data", groups);
        return result;
    }
    
    /**
     * 创建用户组
     */
    @PostMapping("/create")
    @ResponseBody
    public Map<String, Object> createGroup(@RequestBody UserGroup group) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户组名称是否已存在
        UserGroup existingGroup = userGroupService.getGroupByName(group.getGroupName());
        if (existingGroup != null) {
            result.put("success", false);
            result.put("message", "用户组名称已存在");
            return result;
        }
        
        group.setCreateTime(new Date());
        boolean success = userGroupService.createGroup(group);
        
        result.put("success", success);
        if (success) {
            result.put("message", "创建用户组成功");
        } else {
            result.put("message", "创建用户组失败");
        }
        return result;
    }
    
    /**
     * 更新用户组
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateGroup(@RequestBody UserGroup group) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户组是否存在
        UserGroup existingGroup = userGroupService.getGroupById(group.getId());
        if (existingGroup == null) {
            result.put("success", false);
            result.put("message", "用户组不存在");
            return result;
        }
        
        // 检查用户组名称是否已被其他用户组使用
        UserGroup groupWithSameName = userGroupService.getGroupByName(group.getGroupName());
        if (groupWithSameName != null && !groupWithSameName.getId().equals(group.getId())) {
            result.put("success", false);
            result.put("message", "用户组名称已被使用");
            return result;
        }
        
        boolean success = userGroupService.updateGroup(group);
        
        result.put("success", success);
        if (success) {
            result.put("message", "更新用户组成功");
        } else {
            result.put("message", "更新用户组失败");
        }
        return result;
    }
    
    /**
     * 删除用户组
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteGroup(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户组是否存在
        UserGroup existingGroup = userGroupService.getGroupById(id);
        if (existingGroup == null) {
            result.put("success", false);
            result.put("message", "用户组不存在");
            return result;
        }
        
        boolean success = userGroupService.deleteGroup(id);
        
        result.put("success", success);
        if (success) {
            result.put("message", "删除用户组成功");
        } else {
            result.put("message", "删除用户组失败");
        }
        return result;
    }
    
    /**
     * 获取用户组成员
     */
    @GetMapping("/{groupId}/members")
    @ResponseBody
    public Map<String, Object> getGroupMembers(@PathVariable Integer groupId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户组是否存在
        UserGroup existingGroup = userGroupService.getGroupById(groupId);
        if (existingGroup == null) {
            result.put("success", false);
            result.put("message", "用户组不存在");
            return result;
        }
        
        List<User> members = userGroupService.getUsersByGroupId(groupId);
        result.put("success", true);
        result.put("data", members);
        return result;
    }
    
    /**
     * 添加用户到用户组
     */
    @PostMapping("/{groupId}/addUser/{userId}")
    @ResponseBody
    public Map<String, Object> addUserToGroup(@PathVariable Integer groupId, @PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户组是否存在
        UserGroup existingGroup = userGroupService.getGroupById(groupId);
        if (existingGroup == null) {
            result.put("success", false);
            result.put("message", "用户组不存在");
            return result;
        }
        
        // 检查用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        
        boolean success = userGroupService.addUserToGroup(groupId, userId);
        
        result.put("success", success);
        if (success) {
            result.put("message", "添加用户到用户组成功");
        } else {
            result.put("message", "添加用户到用户组失败");
        }
        return result;
    }
    
    /**
     * 从用户组移除用户
     */
    @PostMapping("/{groupId}/removeUser/{userId}")
    @ResponseBody
    public Map<String, Object> removeUserFromGroup(@PathVariable Integer groupId, @PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户组是否存在
        UserGroup existingGroup = userGroupService.getGroupById(groupId);
        if (existingGroup == null) {
            result.put("success", false);
            result.put("message", "用户组不存在");
            return result;
        }
        
        // 检查用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        
        boolean success = userGroupService.removeUserFromGroup(groupId, userId);
        
        result.put("success", success);
        if (success) {
            result.put("message", "从用户组移除用户成功");
        } else {
            result.put("message", "从用户组移除用户失败");
        }
        return result;
    }
    
    /**
     * 获取可添加到用户组的用户列表（不在当前用户组中的用户）
     */
    @GetMapping("/{groupId}/availableUsers")
    @ResponseBody
    public Map<String, Object> getAvailableUsers(@PathVariable Integer groupId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户组是否存在
        UserGroup existingGroup = userGroupService.getGroupById(groupId);
        if (existingGroup == null) {
            result.put("success", false);
            result.put("message", "用户组不存在");
            return result;
        }
        
        // 获取所有用户
        List<User> allUsers = userService.getAllUsers();
        
        // 获取当前用户组中的用户
        List<User> groupUsers = userGroupService.getUsersByGroupId(groupId);
        
        // 移除已在用户组中的用户
        allUsers.removeIf(user -> groupUsers.stream().anyMatch(groupUser -> groupUser.getId().equals(user.getId())));
        
        result.put("success", true);
        result.put("data", allUsers);
        return result;
    }
} 